package com.kingyun.gpsinspection.purificationservice.services.jsm.innerservice.impl.Config;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cqhilink.api.common.utils.UniqueUtil;
import com.kingyun.gpsinspection.purificationservice.common.enums.OrganizationLevelEnum;
import com.kingyun.gpsinspection.purificationservice.common.enums.TreeIconSkinEnum;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.jsm.ConfigItemMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.jsm.EntityProMapper;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.*;
import com.kingyun.gpsinspection.purificationservice.facade.model.webservicesmodel.EntityValue;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.config.JsmConfigItemService;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.config.JsmConfigService;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.organization.JsmOrganizationService;
import com.kingyun.gpsinspection.purificationservice.services.jsm.innerservice.util.OrgTreeUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.*;

/**
 * @Author 卢曼成
 * @Description 二次组态子项接口实现类
 * @CreateDateTime 2017-05-02 9:07
 **/
public class JsmConfigItemServiceImpl implements JsmConfigItemService {
    @Autowired
    private ConfigItemMapper configItemMapper;
    @Autowired
    private JsmConfigService configService;
    @Autowired
    private JsmOrganizationService organizationService;
    @Autowired
    private EntityProMapper entityProMapper;
    @Value("#{configProperties['opc_url']}")
    private String configUril;

    /**
     * 根据ID删除
     *
     * @param configItemId
     * @return
     */
    @Override
    public int deleteByPrimaryKey(String configItemId) {
        return configItemMapper.deleteByPrimaryKey(configItemId);
    }

    /**
     * 添加
     *
     * @param record
     * @return
     */
    @Override
    public int insert(ConfigItem record) {
        return configItemMapper.insert(record);
    }

    /**
     * 非空添加
     *
     * @param record
     * @return
     */
    @Override
    public int insertSelective(ConfigItem record) {
        return 0;
    }

    /**
     * 根据ID查询
     *
     * @param configItemId
     * @return
     */
    @Override
    public ConfigItem selectByPrimaryKey(String configItemId) {
        return configItemMapper.selectByPrimaryKey(configItemId);
    }

    /**
     * 非空修改
     *
     * @param record
     */
    @Override
    public int updateByPrimaryKeySelective(ConfigItem record) {
        return configItemMapper.updateByPrimaryKeySelective(record);
    }

    /**
     * 修改
     *
     * @param record
     * @return
     */
    @Override
    public int updateByPrimaryKey(ConfigItem record) {
        return configItemMapper.updateByPrimaryKey(record);
    }

    /**
     * @Author 卢曼成
     * @Description 根据条件查询集合
     * @CreateDateTime 2017/5/2 8:25
     **/
    @Override
    public List<ConfigItem> selectByParamList(ConfigItem record) {
        return configItemMapper.selectByParamList(record);
    }

    /**
     * @param list
     * @return int
     * @Author 卢曼成
     * @Description 批量添加
     * @CreateDateTime 2017/5/2 8:25
     */
    @Override
    public int insertList(List<ConfigItem> list) {
        return configItemMapper.insertList(list);
    }

    /**
     * @param list
     * @return int
     * @Author 卢曼成
     * @Description 批量修改
     * @CreateDateTime 2017/5/2 8:25
     */
    @Override
    public int updateList(List<ConfigItem> list) {
        return configItemMapper.updateList(list);
    }

    /**
     * @param list
     * @return int
     * @Author 卢曼成
     * @Description 批量逻辑删除
     * @CreateDateTime 2017/5/2 8:25
     */
    @Override
    public int deleteList(List<ConfigItem> list) {
        return configItemMapper.deleteList(list);
    }

    /**
     * @param list
     * @return int
     * @Author 卢曼成
     * @Description 批量逻辑删除
     * @CreateDateTime 2017/5/2 8:25
     */
    @Override
    public int deleteByIdList(List<String> list) {
        return configItemMapper.deleteByIdList(list);
    }

    /**
     * @param param
     * @return int
     * @Author 卢曼成
     * @Description 添加修改逻辑
     */
    @Override
    public int saveOrUpdate(ConfigItem param) {
        if (StringUtils.isEmpty(param.getConfigId())) {
            return 0;
        }
        List<ConfigItem> addList = new ArrayList<ConfigItem>();
        List<ConfigItem> updateList = new ArrayList<ConfigItem>();
        if (StringUtils.isNotEmpty(param.getAddOpc())) {
            addList = JSONArray.parseArray(param.getAddOpc(), ConfigItem.class);
        }
        if (StringUtils.isNotEmpty(param.getModifyOpc())) {
            updateList = JSONArray.parseArray(param.getModifyOpc(), ConfigItem.class);
        }
        Date date = new Date();
        String employeeId = param.getCreatorId();
        int num = 0;
        if (updateList.size() > 0) {
            for (ConfigItem ci : updateList) {
                ci.setOperateId(employeeId);
                ci.setOperateDT(date);
            }
            num += configItemMapper.updateList(updateList);
        }
        if (addList.size() > 0) {
            for (ConfigItem ci : addList) {
                ci.setConfigId(param.getConfigId());
                ci.setConfigItemId(UniqueUtil.uuid());
                ci.setCreateDT(date);
                ci.setCreatorId(employeeId);
                ci.setOperateId(employeeId);
                ci.setOperateDT(date);
            }
            num += configItemMapper.insertList(addList);
        }
        return num;
    }

    /**
     * @param employee
     * @return int
     * @Author 卢曼成
     * @Description org组织树
     */
    @Override
    public List<Ztree> configItemTree(Employee employee, String keyword) throws Exception {
        EntityPro ep = new EntityPro();
        ep.setEntityId(employee.getOrgId());
        ep.setOrgLevelId(OrganizationLevelEnum.ORG_LEVEL_STATION.getCode());
        ep.setKeyword(keyword);
        List<String> strList = entityProMapper.selectByEntityListCode(ep);
        List<Ztree> demotree = new ArrayList<Ztree>();
        List<Organization> orgList = organizationService.getOrganizationList(employee, OrganizationLevelEnum.ORG_LEVEL_BRANCH.getCode(), OrganizationLevelEnum.ORG_LEVEL_STATION.getCode());
        Organization organization = new Organization();
        organization.setOrgLevelId(OrganizationLevelEnum.ORG_LEVEL_STATION.getCode());
        List<Organization> orgItemList = organizationService.selectByOrgItem(organization);

        if (StringUtils.isNotEmpty(keyword)) {
            Set<Organization> newList = new HashSet<Organization>();
            disposeOrg(newList, orgList, strList);
            OrgTreeUtil.orgToTreeTrue(new ArrayList<Organization>(newList), orgItemList, strList, demotree, employee.getOrgId());
        } else
            OrgTreeUtil.orgToTreeTrue(orgList, orgItemList, strList, demotree, employee.getOrgId());

        List<EntityPro> epList = entityProMapper.selectByEntityList(ep);
        if (epList != null && epList.size() > 0) {
            for (EntityPro e : epList) {
                Ztree demo = new Ztree();
                demo.setIconSkin(TreeIconSkinEnum.ICON_DEVICE_CHARA.getDesc());
                demo.setId(e.getDevicePropertyId());
                demo.setpId(e.getEntityId());
                demo.setName(e.getPropertyName());
                demo.setObj(e);
                demotree.add(demo);
            }
            return demotree;
        }
        return null;
    }

    //处理采集点对应ORG
    private void disposeOrg(Set<Organization> newList, List<Organization> orgList, List<String> strList) {
        if (strList != null && orgList != null) {
            List<Organization> list = new ArrayList<Organization>();
            Iterator<Organization> it = orgList.iterator();
            while (it.hasNext()) {
                Organization org = it.next();
                if (strList.contains(org.getOrgId())) {
                    list.add(org);
                    newList.add(org);
                    it.remove();
                }
            }
            if (list.size() > 0) {//根据ORG上级ID获取上级信息
                for (Organization org : list) {
                    recursionOrg(newList, orgList, org.getParentOrgId());
                }
            }
        }
    }

    //根据ORG上级ID获取上级信息
    public void recursionOrg(Set<Organization> newList, List<Organization> orgList, String id) {
        if (orgList.size() > 0) {
            Iterator<Organization> it = orgList.iterator();
            while (it.hasNext()) {
                Organization org = it.next();
                if (id.equals(org.getOrgId())) {
                    newList.add(org);
                    recursionOrg(newList, orgList, org.getParentOrgId());//递归
                }
            }
        }
    }

    /**
     * 根据条件获取初始化数据
     *
     * @param param
     * @return List<ConfigItem>
     * @Author 卢曼成
     */
    @Override
    public List<ConfigItem> getInitData(ConfigItem param) throws Exception {
        List<ConfigItem> ciList = configItemMapper.selectByParamList(param);
        if (ciList != null && ciList.size() > 0) {
            if (param.getCreatorName().equalsIgnoreCase("true")) {
                List<String> itemName = new ArrayList<String>();
                for (ConfigItem e : ciList) {
                    itemName.add(e.getPropertyOpc());
                }
                String sb = "{\"itemName\":" + JSONArray.toJSON(itemName) + "}";
//                sb = "{\"itemName\":[\"Channel1.Device1.12345678901234567\",\"Channel1.Dvice1.12345678901234568\"]} ";
                String str = null;
//                try {
//                    //处理连接超时
//                    str = HttpClientUtil.httpPostWithJson(configUril, sb);
//                } catch (Exception e) {
//                    return ciList;
//                }
                str = "{\"value\": [[\"1\", 129011111111111.0132132132132, \"Good\", \"05/03/17 10:27:45\"], [\"2\", \"1.13213213213213\", \"Good\", \"05/03/17 10:27:45\"],[\"3\", \"1.13213132132\", \"Good\", \"05/03/17 10:27:45\"]" +
                        "[\"4\", \"12345.132132465\", \"Good\", \"05/03/17 10:27:45\"],[\"5\", \"365465.0054564646\", \"Good\", \"05/03/17 10:27:45\"]]}";
                if (StringUtils.isNotEmpty(str) && str.contains("value")) {
                    EntityValue ev = JSONObject.parseObject(str, EntityValue.class);
                    List<String> list = ev.getValue();
                    if (list != null && list.size() > 0) {
                        for (ConfigItem ci : ciList) {
                            ci.setPropertyOpcValue(isValue(list, ci.getPropertyOpc()));
                        }
                    }
                }
            }
        }
        return ciList;
    }

    /**
     * 根据条件获取初始化数据
     *
     * @param opcIds
     * @return List<ConfigItem>
     * @Author 卢曼成
     */
    @Override
    public List<ConfigItem> getRefreshData(String opcIds) throws Exception {
        if (StringUtils.isNotEmpty(opcIds)) {
            List<String> strList = JSONArray.parseArray(opcIds, String.class);
            String sb = "{\"itemName\":" + opcIds + "}";
//            sb = "{\"itemName\":[\"Channel1.Device1.12345678901234567\",\"Channel1.Dvice1.12345678901234568\"]}";
            String str = null;
//            try {
//                //处理连接超时
//                str = HttpClientUtil.httpPostWithJson(configUril, sb);
//            } catch (Exception e) {
//                return null;
//            }
            str = "{\"value\": [[\"1\", 129011111111111.0132132132132, \"Good\", \"05/03/17 10:27:45\"], [\"2\", \"1.13213213213213\", \"Good\", \"05/03/17 10:27:45\"],[\"3\", \"1.13213132132\", \"Good\", \"05/03/17 10:27:45\"]" +
                    "[\"4\", \"12345.132132465\", \"Good\", \"05/03/17 10:27:45\"],[\"5\", \"365465.0054564646\", \"Good\", \"05/03/17 10:27:45\"]]}";
            if (StringUtils.isNotEmpty(str) && str.contains("value")) {
                EntityValue ev = JSONObject.parseObject(str, EntityValue.class);
                List<String> list = ev.getValue();
                if (list != null && list.size() > 0) {
                    List<ConfigItem> ciList = new ArrayList<ConfigItem>();
                    for (String s : strList) {
                        ConfigItem ci = new ConfigItem();
                        ci.setPropertyOpcValue(isValue(list, s));
                        ci.setPropertyOpc(s);
                        ciList.add(ci);
                    }
                    return ciList;
                }
            }
        }
        return null;
    }

    /**
     * 处理特性值对应OPC值
     *
     * @param list
     * @param opcId
     * @return
     */
    private String isValue(List<String> list, String opcId) {
        for (String s : list) {
            List<String> strList = JSONArray.parseArray(s, String.class);
            if (strList.get(0).equals(opcId)) {
                return strList.get(1);
            }
        }
        return null;
    }

}
